var isTest = false;
var domain = window.location.host;
var imgcom, resource, filecom;
var subdomain = '';
var httpcom = 'http://' + domain + '/';
if (isTest) {
	imgcom = 'http://www.youshouru.com/img/image/';
	filecom = 'http://www.youshouru.com/img/';
	resource = 'http://www.test.com:8088/';

    resource = 'http://s.zhuan.net/';

	domain = "www.test.com";
	subdomain = 'test.com';
} else {
	imgcom = 'http://www.youshouru.com/img/image/';
	filecom = 'http://www.youshouru.com/img/';
	resource = 'http://s.zhuan.net/';

    var source = $('#jsbase').attr('source');
	if(source == '8d4e31223ee9d91c') {//ysrAdmin
        httpcom = 'http://' + domain + '/8d4e31223ee9d91c/';
    } if(source == 'fenzhan') {//ysrFenzhanAdmin
        httpcom = 'http://' + domain + '/fenzhan/';
    } else if(source == 'shiyong') {//shiyong
        imgcom = 'http://img.youshouru.com/';
    } else if(source == '705fe851b806203f') {//shiyongAdmin
        httpcom = 'http://' + domain + '/705fe851b806203f/';
        imgcom = 'http://img.youshouru.com/';
    }

	if(domain.indexOf("www") != -1) {
		subdomain = domain.substring(4);
	} else if(domain.indexOf("shiyong") != -1) {
		subdomain = domain.substring(7);
	} else {
		subdomain = domain;
	}
}
var imgBackground = resource + 'image/upload.png';
var baidu = {
	1001 : '2ee16ae430e0673d8bfb7b6dd9c92c13',
	1004 : '9ffb912ab1763a1830e7faa3db887079',
	1118 : '93d1d81a9459707edb2c301c582be258',
	1186 : '2653945bc899a420c3df3748d915c1e3',
	1203 : '7e587e2fbe0d6665b7a0a02f37635101',
	1737 : 'ccbc0a57acdd8c30c5f64adfa24ae7fb',
	1013 : '2d6e6fe1915e822a61a1dabc4fb3ff32',
	2638 : '38eccd70bf9af2de8a65664dd3eeb0b2'
};

function doLogout() {
	cookie.remove('apptoken');
	Call.ajaxSend('logout.do', null, function(d){
		Call.httpLoad('');
	});
}

var API = {
	ajaxSend : function(url, data, callback) {
		$.ajax({
			type : (data) ? "POST" : 'GET',
			url : httpcom + url,
			contentType : "application/x-www-form-urlencoded; charset=utf-8",
			dataType : "jsonp",
			data : data,
			cache : false,
			success : function(d) {
				callback && callback(d);
			}
		});
	}
};

var Call = {
	ajaxSend : function(url, data, callback) {
		$.ajax({
			type : (data) ? "POST" : 'GET',
			url : httpcom + url,
			contentType : "application/x-www-form-urlencoded; charset=utf-8",
			dataType : "json",
			data : data,
			cache : false,
			success : function(d) {
				callback && callback(d);
			},
			error : function(data,type, err){
                				layer.msg("请求异常，请稍后再试！");
                				console.log("httpSend.error：type="+type + ';err=' + err);
                				console.log('httpSend.error：data=' + data);
           			 }

		});
	},
    ajaxSendFile : function(url, data, callback) {
        $.ajax({
            type : "POST",
            processData: false,
            contentType: false,
            url : url,
            dataType : "json",
            data : data,
            cache : false,
            success : function(d) {
                callback && callback(d);
            },
            error : function(data,type, err){
                layer.msg("请求异常，请稍后再试！");
                console.log("httpSend.error：type="+type + ';err=' + err);
                console.log('httpSend.error：data=' + data);
            }

        });
    },
	httpSend : function(url, data, callback) {
		$.ajax({
			type : (data) ? "POST" : 'GET',
			url : httpcom + url,
			contentType : "application/x-www-form-urlencoded; charset=utf-8",
			data : data,
			cache : false,
			success : function(d) {
				callback && callback(d);
			},
			error : function(data,type, err){
               	 			layer.msg("请求异常，请稍后再试！");
                				console.log("httpSend.error：type="+type + ';err=' + err);
                				console.log('httpSend.error：data=' + data);
            			}
		});
	},
	httpLoad : function(url) {
		if (url) {
			if (url.indexOf('http://') == -1) {
				window.location.href = httpcom + url;
			} else {
				window.location.href = url;
			}
		} else {
			if (url == '') {
				window.location.href = httpcom;
			} else {
				window.location.reload();
			}
		}
	},
	fileLoad : function(file){
		var u = filecom + file;
		$('#target_iframe').attr('src', u);
	}
};

$(function() {
	$(document).on('click', 'a', function() {
		if ($(this).attr('href') == '#') {
			return false;
		}
		return true;
	});
});

function getImgvcode(imgbtn) {
	imgbtn = imgbtn ? '#' + imgbtn : '#imgvcode-btn';
	var url = httpcom + 'imgvcode.do?t=';
	$(imgbtn).click(function() {
		var e = $(this);
		e.find('img').attr('src', url + new Date().getTime());
	});

	$(imgbtn).find('img').attr('src', url + new Date().getTime());
}

function getVcode(source) {
	this.lefttime = 0;
	this.timeer = null;

	var e = this;
	this.getBindEvent = function() {
		$("#get_vcode_btn").bind("click", function() {
			e.getVcodeFun();
		});
	};
	this.getVcodeFun = function() {
		$("#get_vcode_btn").unbind("click");

		var mobile = $("#phone").val();
		if (!new RegExp("^0?(13|15|17|18|14)[0-9]{9}$").test(mobile)) {
			layer.msg('手机号码格式错误');
			e.getBindEvent();
			return false;
		}

		var imgvcode = $("#imgvcode").val();
		if (imgvcode == '') {
			layer.msg('请输入验证码');
			e.getBindEvent();
			return false;
		}
		var url = 'vcode.do?source=' + source + '&phone=' + mobile + '&imgvcode=' + imgvcode;

		Call.ajaxSend(url, null, function(d) {
			if (d.success) {
				e.lefttime = 60;
				e.countdown();
				myLayer.tips('vcode', '验证码已发送，请输入验证码');
			} else {
				e.getBindEvent();
				layer.msg(d.msg);
			}
		});
	};
	this.countdown = function() {
		clearTimeout(e.timeer);
		$("#get_vcode_btn").html(e.lefttime + "秒后发送");
		e.lefttime--;
		if (e.lefttime > 0) {
			e.timeer = setTimeout(e.countdown, 1000);
		} else {
			e.lefttime = 60;
			$("#get_vcode_btn").html("发送验证码");
			e.getBindEvent();
		}
	};
	e.getBindEvent();
}

var cookie = {
	add : function(n, t, i) {
	    var r, u;
	    i ? (r = new Date, r.setTime(r.getTime() + i * 864e5), u = "; expires=" + r.toGMTString()) : u = "";
	    document.cookie = n + "=" + t + u + "; domain="+subdomain+"; path=/";
	},
	remove : function(n) {
		cookie.add(n, '');
	},
	get : function(n) {
	    for (var t, r = n + "=", u = document.cookie.split(";"), i = 0; i < u.length; i++) {
	        for (t = u[i]; t.charAt(0) == " "; )
	            t = t.substring(1, t.length);
	        if (t.indexOf(r) == 0)
	            return t.substring(r.length, t.length);
	    }
	    return null;
	}
};

var date = {
	initDate : function(container) {
		$(container).datetimepicker({
			language : 'zh-CN',
			autoclose : true,
			minView : 2,
			format : 'yyyy-mm-dd'
		});
	},
	initTime : function(container) {
		$(container).datetimepicker({
			language : 'zh-CN', // 汉化
			autoclose : true
		// 选择日期后自动关闭
		});
	},
	initMonth : function(container) {
		$(container).datetimepicker({
			format : 'yyyy-mm',
			weekStart : 1,
			autoclose : true,
			startView : 3,
			minView : 3,
			forceParse : false,
			language : 'zh-CN'
		});
	}
};

var myLayer = {
	tips : function(id, msg){
		layer.tips(msg, '#' + id,  {
		  tips: [1, '#3595CC'],
		  time: 4000
		});
	}
};

/**
 * 实时动态强制更改用户录入 arg1 inputObject
 */
function amount(th){
    var regStrs = [
        ['^0(\\d+)$', '$1'], // 禁止录入整数部分两位以上，但首位为0
        ['[^\\d\\.]+$', ''], // 禁止录入任何非数字和点
        ['\\.(\\d?)\\.+', '.$1'], // 禁止录入两个以上的点
        ['^(\\d+\\.\\d{2}).+', '$1'] // 禁止录入小数点后两位以上
    ];
    for(var i=0; i<regStrs.length; i++){
        var reg = new RegExp(regStrs[i][0]);
        th.value = th.value.replace(reg, regStrs[i][1]);
    }
}
 
/**
 * 录入完成后，输入模式失去焦点后对录入进行判断并强制更改，并对小数点进行0补全 arg1 inputObject
 */
function overFormat(e){
    var v = e.val();
    if(v === ''){
        v = '0';
    }else if(v === '0'){
        v = '0';
    }else if(v === '0.'){
        v = '0.00';
    }else if(/^0+\d+\.?\d*.*$/.test(v)){
        v = v.replace(/^0+(\d+\.?\d*).*$/, '$1');
        v = inp.getRightPriceFormat(v).val;
    }else if(/^0\.\d$/.test(v)){
        v = v + '0';
    }else if(!/^\d+\.\d{2}$/.test(v)){
        if(/^\d+\.\d{2}.+/.test(v)){
            v = v.replace(/^(\d+\.\d{2}).*$/, '$1');
        }else if(/^\d+$/.test(v)){
            //v = v ;
        }else if(/^\d+\.$/.test(v)){
            v = v + '00';
        }else if(/^\d+\.\d$/.test(v)){
            v = v + '0';
        }else if(/^[^\d]+\d+\.?\d*$/.test(v)){
            v = v.replace(/^[^\d]+(\d+\.?\d*)$/, '$1');
        }else if(/\d+/.test(v)){
            v = v.replace(/^[^\d]*(\d+\.?\d*).*$/, '$1');
            ty = false;
        }else if(/^0+\d+\.?\d*$/.test(v)){
            v = v.replace(/^0+(\d+\.?\d*)$/, '$1');
            ty = false;
        }else{
            v = '0';
        }
    }
    e.val(v);
}

var pageLoad = {
	price : function(){
		$('.amount').on('keyup', function(){
			amount($(this));
		});
		$('.amount').on('blur', function(){
			overFormat($(this));
		});
	},
	radio : function(name, selected, callback) {
		if(selected == '') {
			selected = '0';
		}
		$("input[name=" + name + "][value=" + selected + "]").attr("checked",
				true);

		var checked = $('input:radio[name=' + name + ']:checked').val();
		if (!checked) {
			$('input:radio[name=' + name + ']')[0].checked = true;
			checked = $('input:radio[name=' + name + ']:checked').val();
		}
		if (callback) {
			callback(checked);
			$("input[name=" + name + "]").on('click', function() {
				var c = $('input:radio[name=' + name + ']:checked').val();
				callback(c);
			});
		}
	},
	checkbox : function() {
		$('input[type=checkbox]').each(function(index, el) {
			var e = $(this);
			var v = e.attr('data');
			var c = e.val();
			if (v == c) {
				e.attr("checked", true);
			}
		});
	},
	select : function() {
		$('select').each(function(index, el) {
			var e = $(this);
			var v = e.attr('data');
			if (v != '') {
				e.val(v);
			}
		});
	}
};

document.addEventListener("error", function(e){
	var elem = e.target;
	if(elem.tagName.toLowerCase() == 'img'){
		//elem.src = imgBackground;
	}
}, true);